//客户资料管理

interface IClientInfoManagentDetailViewModel {
    /**
     * 编号
     */
    id?: string;
    /**
     * 名称
     */
    name: string;
    /**
     * 客户资料类别
     */
    type: string;
    /**
     * 客户资料级别
     */
    level: string;
    /**
     * 内容
     */
    content: string;
    /**
     * 点击事件
     */
    click: () => void;

    
}

interface IClientInfoManagentViewModel extends IBaseViewModel<IClientInfoManagentQueryTerms> {
    /**
     * ui-grid控制
     */
    gridOptions: uiGrid.IGridOptionsOf<ClientInfoListItemResponse>;
    /**
     * 资料类别下拉
     */
    typeDropDown: ValueListItemResponse[];
    /**
     * 资料级别下拉
     */
    levelDropDown: ValueListItemResponse[];
    /**
     * 添加/编辑详情
     */
    detail: IClientInfoManagentDetailViewModel;
    /**
     * 添加客户资料
     */
    addClientInfo: () => void;
    /**
     * 编辑客户资料
     */
    editClientInfo: (id: string) => void;
    /**
     * 删除客户资料
     */
    deleteClientInfo: (id: string) => void;
    /**
     * 客户单位名称
     */
    clientName:string;
    /**
     * 列表高
     */
    heightA:number;
    /**
     * 附件列表
     */
    attachmentUploader:any;
    /**
     * 是否允许附件上传
     */
    allowAttachmentUploader:boolean;
    /**
     * 点击附件上传的状况
     */
    handleItemUploader: (item:any) => void;
    /**
     * 上传全部附件
     */
    uploadAllFile: () => void;
    /**
     * 下载附件
     */
    handleItemDownLoader: (item) =>void;
    /**
     * 删除附件
     */
    handleItemDelete: (item) =>void;
    
    /**
     * 更改资料类别时的回调函数
     */
    handleInfoTypeChange: ()=>void;
}

interface IClientInfoManagentQueryTerms {
    /**
     * 资料名称
     */
    name: string;
    /**
     * 资料类别
     */
    type: string;
    /**
     * 资料级别
     */
    level: string;
}

class ClientInfoManagentController extends ListController<IClientInfoManagentViewModel, IClientInfoManagentQueryTerms> {
    gridApi: uiGrid.IGridApiOf<ClientInfoListItemResponse>;
    enterpriseId: string;
    uploaderList: Array<attachmentList>;
    ALLOWFILETYPE = ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'gif', 'png', 'jpg', 'jpeg','tiff','bmp'];
    constructor($scope: IClientInfoManagentViewModel, private clientInfoService: IClientInfoService, private valueService: IValueService,
        private $ngBootbox: BootboxService, private $location: ng.ILocationService,
        private routeService:routeService,private commonService:commonService,
        private ossUploaderService:ossUploaderService) {
        super($scope);
        this.init();
    }

    init(): void {
        super.init();
        this.enterpriseId = this.$location.search().id;
        this.enterpriseId = JSON.parse(window.localStorage.getItem("client").toString()).clientId;
        this.$scope.clientName = JSON.parse(window.localStorage.getItem("client").toString()).clientName;

        this.$scope.addClientInfo = this.showAddClientInfoDialog;
        this.$scope.editClientInfo = this.showEditClientInfoDialog;
        this.$scope.deleteClientInfo = this.showDeleteClientInfoDialog;
        $('#content')['wysiwyg']({ fileUploadError: this.showErrorAlert} );
        this.$scope.queryTerms = {
            name: "",
            type: "",
            level: ""
        };

        this.$scope.gridOptions = {
            enableSorting: false,
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 30],
            columnDefs: [
                { name: "序号", field: "index", enableColumnMenu: false },
                { name: "资料名称", field: "name", enableColumnMenu: false },
                { name: "资料类型", field: "infoType", enableColumnMenu: false },
                { name: "资料级别", field: "infoLevel", enableColumnMenu: false },
                { name: "创建时间", field: "createTime", enableColumnMenu: false },
                {
                    name: "操作",
                    cellFilter: 'checkmark',
                    cellTemplate: '<a data-toggle="modal" title="编辑" data-target="#clientinfo" class="fa fa-edit m-l-xs primary text-info" ng-click="grid.appScope.editClientInfo(row.entity.id)"></a> <a class="primary fa fa-trash-o text-danger" title="删除" ng-click="grid.appScope.deleteClientInfo(row.entity.id)"></a>',
                    enableColumnMenu: false
                }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
            }
        };
        this.loadTypeDropDown();
        this.loadLevelDropDown();
        this.query();
        this.uploaderList = [];
        this.$scope.allowAttachmentUploader = true;
        this.$scope.handleItemUploader = this.handleItemUploader;
        this.$scope.uploadAllFile = this.uploadAllFile;
        this.$scope.handleItemDownLoader = this.handleItemDownLoader;
        this.$scope.handleItemDelete = this.handleItemDelete;
        this.$scope.handleInfoTypeChange = () =>{
            if(this.setAllowUploader() ===1){
                this.$ngBootbox.alert('当资料类别为合同资料时，只能上传一个附件。请删除多余附件');
            }
        }
        


       

        const OssFile = this.ossUploaderService.getOssFile();
        this.$scope.attachmentUploader =new OssFile(this.$scope,this.$scope.attachmentUploader,{uploaderList:this.uploaderList,tag:1,multiple:true});
        this.$scope.attachmentUploader.onSuccess = (fileItem: any) => { this.onSuccessItem("", fileItem.fileName, fileItem.imgSrc, 0, fileItem._file); }
        this.$scope.attachmentUploader.onDelete=(fileItem)=>{
            this.$scope.attachmentUploader.queue=this.$scope.attachmentUploader.queue.filter(it=>it.index!==fileItem.index);
            this.uploaderList=this.uploaderList.filter(it=>it.attachmentName!==fileItem.fileName||it.attachmentPath!==fileItem.imgSrc);

        }
        this.$scope.attachmentUploader.onAfterAddingFile = this.handleAddingFile;


    
    }

    loadData(queryTerms: IClientInfoManagentQueryTerms, skip: number, count: number): void {
        this.clientInfoService.getList(this.enterpriseId, queryTerms.name, queryTerms.type, queryTerms.level, skip, count).then(result => {
            this.$scope.gridOptions.totalItems = result.data.total;
            result.data.data.map((item, index) => item.index = skip++ +1);
            this.$scope.gridOptions.data = result.data.data;

            this.$scope.heightA = (this.$scope.gridOptions.data.length *39)+95;

            if (skip == 0) {
                this.$scope.gridOptions.paginationCurrentPage = 1;
            }
            this.$scope.querying = false;
        }, error => {
            this.$scope.querying = false;
        });
    }

     showErrorAlert(reason, detail):void{
		var msg='';
		if (reason==='unsupported-file-type') { msg = "Unsupported format " +detail; }
		else {
			console.log("error uploading file", reason, detail);
		}
		$('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>'+ 
		 '<strong>File upload error</strong> '+msg+' </div>').prependTo('#alerts');
	};
    /**
     * 读取资料类别下拉数据
     */
    loadTypeDropDown(): void {
        this.$scope.typeDropDown = this.valueService.getClientInfoTypeList().data;
    }

    /**
     * 读取资料级别下拉数据
     */
    loadLevelDropDown(): void {
        this.$scope.levelDropDown = this.valueService.getInfoLevelList().data;
    }

    showDeleteClientInfoDialog = (id: string) => {
        this.$ngBootbox.confirm("确定删除此数据吗？").then(e => {
            this.clientInfoService.delete(id).then(result => {
                this.reload();
            });
        });
    }

    showAddClientInfoDialog = () => {
        this.$scope.title = "添加客户资料";
        this.$scope.detail = {
            name: "",
            type: "",
            level: "",
            content: "",
            click: this.addClientInfo
        };
        $("#content").html("");
        this.$scope.attachmentUploader.queue = [];
        this.uploaderList = [];
    }

    addClientInfo=()=> {
        
        if (!$("#clientInfoForm").valid()) { return }
        var attachmentArr = [];
        this.uploaderList.forEach((item, index) => {
            // attachmentArr.push([item.attachmentId,item.attachmentName,item.attachmentPath,item.attachmentTag]);   
            attachmentArr.push([item.attachmentName, item.attachmentPath]);

        });
        this.$ngBootbox.confirm("确定保存此数据吗？").then(e => {
            this.clientInfoService.add(
                this.enterpriseId,
                this.$scope.detail.name,
                this.$scope.detail.type,
                this.$scope.detail.level,
                $("#content").html(),
                attachmentArr
                //this.$scope.detail.content
            ).then(result => {
                this.reload();
                this.uploaderList = [];
                this.$scope.allowAttachmentUploader = true;
                $("#clientinfo").modal("hide");
            });
        });
    }

    showEditClientInfoDialog = (id: string) => {
        this.$scope.attachmentUploader.queue = [];
        this.uploaderList = [];
        this.$scope.title = "编辑客户资料";
        var validator = $('#clientInfoForm').validate();
        validator.form();
        validator.hideErrors();
        $(".error").removeClass("error");
       
        this.clientInfoService.getDetail(id).then(result => {
            this.$scope.detail = {
                id: id,
                name: result.data.name,
                type: result.data.infoType,
                level: result.data.infoLevel,
                content: result.data.content,
                click: this.editClientInfo
            };
            result.data.attachment.forEach(attach => {
                const temp={
                    attachmentId: attach[0],
                    attachmentName: attach[1],
                    attachmentPath: attach[2],
                    attachmentTag: attach[3],
                }
                this.uploaderList.push(temp);
                this.$scope.attachmentUploader.addByAttach(temp);
                this.setAllowUploader()


               
            });
            
            $("#content").html(result.data.content);
        });
    }

    editClientInfo=()=>{
        let state = this.setAllowUploader();
        switch (state) {
            case 1:this.$ngBootbox.alert('当资料类别为合同资料时，只能上传一个附件。请删除多余附件');
                return;
            case 2:this.$ngBootbox.alert('最多只能上传5个附件。请删除多余附件');return;
            default:
                break;
        }
        var attachmentArr = [];
        this.uploaderList.forEach((item, index) => {
            // attachmentArr.push([item.attachmentId,item.attachmentName,item.attachmentPath,item.attachmentTag]);   
            attachmentArr.push([item.attachmentName, item.attachmentPath]);

        });
        this.$ngBootbox.confirm("确定保存该数据吗？").then(e => {
            this.clientInfoService.edit(
                this.$scope.detail.id,
                this.enterpriseId,
                this.$scope.detail.name,
                this.$scope.detail.type,
                this.$scope.detail.level,
                $("#content").html(),
                attachmentArr
            ).then(result => {
                this.uploaderList = [];
                this.$scope.allowAttachmentUploader = true;
                this.reload();
                $("#clientinfo").modal("hide");
            });
        });
    }


    /**
     * 选择上传文件后
     */
    onSuccessItem(fileId: string, fileName: string, filePath: string, tag: number, file?: any): void {
        console.log(fileName);
        file.fileId = filePath;
        let attachment = {
            attachmentId: fileId,
            attachmentName: fileName,
            attachmentPath: filePath,
            attachmentTag: ""
        };
        this.uploaderList.push(attachment);

        

        
    }
    

    /**
     * 判断是否还能继续上传文件
     */
    setAllowUploader = () =>{
        if(this.$scope.detail.type === "6"&&this.$scope.attachmentUploader.queue.length > 1){
            return 1;  // 资料类型为“合同资料”且上传文件数量大于1；
        }else if(this.$scope.attachmentUploader.queue.length > 5){
            return 2; // 上传文件数量大于5；
        }else {
            return 0; //符合要求
        }
    }

    handleItemUploader = (item) => {
        if(!item.imgSrc){
            // item.upload();
            this.$scope.attachmentUploader.upload(item)
        }
        
    }
    
    uploadAllFile = ()=> {
        this.$scope.attachmentUploader.queue.forEach(item => {
            this.handleItemUploader(item);
        });
    }
    handleItemDownLoader = (item) => {
        // window.location.href = item.imgSrc;
        this.$scope.attachmentUploader.onDownload(item);
    }
    handleItemDelete = (item) =>{
        // item.remove(),
        this.$scope.attachmentUploader.onDelete(item);
        
    }
    handleAddingFile = (item) => {
        let state = this.setAllowUploader();
        switch(state){
            case 1:{
                this.$ngBootbox.confirm('当资料类别为合同资料时，只能上传一个附件').then(result => {
                    this.handleItemDelete(item);
                },reject => {
                    this.handleItemDelete(item);
                });
                return;
            };
            case 2:{
                this.$ngBootbox.confirm('最多只能上传5个附件').then(result => {
                    this.handleItemDelete(item);
                },reject => {
                    this.handleItemDelete(item);
                });
                return;
            }
        }
        
        if(item._file.size > 10*1024*1024){
            this.$ngBootbox.confirm('文件大小不能超过10M').then(result => {
                this.handleItemDelete(item);
            },reject => {
                this.handleItemDelete(item);
            });
            
        }else {
            var fileType = item._file.name.split('.').pop().toLowerCase();
            if(this.ALLOWFILETYPE.indexOf(fileType) === -1){
                this.$ngBootbox.confirm('不支持该文件类型').then(result => {
                    this.handleItemDelete(item);
                },reject=>{
                    this.handleItemDelete(item);
                })
            }
        }
        
    }
    
}


angular.module("tms").controller("clientInfoManagentController", ["$scope", "clientInfoService", "valueService", "$ngBootbox",
 "$location","routeService","commonService","ossUploaderService", ClientInfoManagentController]);


// http://192.168.0.25:5005/tms/attachmentdownload/9?token=6364325256403177988756E3427588C64D130107812B34CC9D&fileId=14e5ece8-21ae-42bf-bbcb-200b43c8ab3b